package com.lsh.netty.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @author ：LiuShihao
 * @date ：Created in 2021/6/28 12:23 下午
 * @desc ：
 * WebSocketServer服务端功能介绍：
 * 支持WebSocket的浏览器通过WebSocket协议发送请求消息给服务端，服务端对请求消息进行判断，如果是合法的WebSocket请求
 * 则获取请求消息文本，并在后面追加字符串"欢迎使用Netty WebSocket 服务，现在时刻：系统时间"
 */
public class WebSocketServer {

    public void run(int port) throws Exception{
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try{
            ServerBootstrap b = new ServerBootstrap();
            b.group(boosGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //添加HttpServerCodec：将请求和应答消息解码或者解码为HTTP消息
                            pipeline.addLast("http-codec",new HttpServerCodec());
                            //增加HttpObjectAggregator：目的是将HTTP消息的多个部分组合成一条完整的HTTP消息
                            pipeline.addLast("aggregator",new HttpObjectAggregator(65536));
                            // ChunkedWriteHandler:来向客户端发送HTML5文件，它主要用于支持浏览器和服务端进行WebSocket通信
                            ch.pipeline().addLast("http-chunked",new ChunkedWriteHandler());
                            //增加WebSocket服务端Handler
                            pipeline.addLast("handler",new WebSocketServerHandler());

                        }
                    });
            Channel ch = b.bind(port).sync().channel();
            System.out.println("Web socket server started at port "+port);
            System.out.println("open your browser and navigate to http://localhost:"+port+"/");
            ch.closeFuture().sync();
        }finally {
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        new WebSocketServer().run(port);
    }
}
